// @Desc:
// @CreateTime: 2020/10/18
package customer

import (
    "fmt"
    "github.com/gin-gonic/gin"
    . "mycrm.com/controller"
    mlog "mycrm.com/log"
    . "mycrm.com/module"
    "mycrm.com/module/customer"
    "mycrm.com/module/user"
    "mycrm.com/module/visit"
    "net/http"
    "strconv"
    "time"
)

// 员工的话就只能看自己的, 其他级别都可以看
func List(c *gin.Context) {
    var (
        customerInfo  []map[string]interface{}
        pageSize      int
        total         int64 // 总条数
        curUserRoleId int
    )
    pageStr := c.Query("cur_page")
    pageNum, _ := strconv.Atoi(pageStr)
    name := c.Query("search_name")
    phone := c.Query("search_phone")
    startime := c.Query("search_starttime")
    endtime := c.Query("search_endtime")
    uid := c.Query("uid")
    // 首先判断下该用户的角色
    Db.Model(&user.CrmUser2role{}).Select("role_id").Where("user_id = ?", uid).Scan(&curUserRoleId)
    mlog.Log.Info("role: ", curUserRoleId)
    tx := Db.Table("crm_customer as c")
    if name != "" {
        tx.Where("c.name = ?", name)
    }
    // 当前用户是 员工的话
    if curUserRoleId == 5 {
        tx.Where("c.user_id = ?", uid)
    }
    // 当前用户是组长, 只能查看该组的所有客户
    if curUserRoleId == 4 {
        var (
            userIdArr []int
            groupId int
        )
        Db.Model(&user.CrmUser{}).Where("id = ?", uid).Select("group_id").Scan(&groupId)
        Db.Model(&user.CrmUser{}).Where("group_id = ?", groupId).Select("id").Scan(&userIdArr)
        tx.Where("c.user_id IN (?)", userIdArr)
    }
    if phone != "" {
        tx.Where("c.phone = ?", phone)
    }
    if startime != "" && endtime != "" {
        tx.Where("c.next_visit_at BETWEEN ? AND ?", startime, endtime)
    }
    tx.Count(&total).Select("c.*").Limit(pageSize).Offset((pageNum - 1) * pageSize).Order("created_at DESC").Scan(&customerInfo)
    mlog.Log.Info("customerInfo: ", customerInfo)
    c.JSON(http.StatusOK, &Response{
        Status:      1,
        Data:        customerInfo,
        Total:       int(total),
        CurrentPage: pageNum,
    })

}

// add customer
func Add(c *gin.Context) {
    var (
        customerInfo, hasCustomer customer.Customer
        // userId int   // 用户 id
        userInfo user.CrmUser
    )
    if err := c.BindJSON(&customerInfo); err != nil {
        mlog.Log.Error("c.BindJSON(&customerInfo) is failed, err: ", err)
        return
    }
    mlog.Log.Info("reqData : ", customerInfo)
    resp := &Response{
        Status: 1,
        Msg:    "新增成功",
    }
    // 首先查询下该客户是否已存在, 如果存在的话就不能新建
    Db.Find(&hasCustomer, "phone = ?", customerInfo.Phone)
    if hasCustomer.UserId > 0 { // 表示该客户已经有销售在维护了
        // 查询是哪个人有的该客户
        Db.Find(&userInfo, hasCustomer.UserId)
        resp.Status = 0
        resp.Msg = fmt.Sprintf("该用户是 %s 的客户", userInfo.Name)
        // 判断是不是本人已创建
        if hasCustomer.UserId == customerInfo.UserId { // 创建者的客户
            resp.Msg = "你已创建过该客户"
        }
    } else {
        // 准备保存数据
        // 下次回访时间
        nextVisitTime, _ := strconv.Atoi(customerInfo.NextVisitDay)
        customerInfo.NextVisitAt = int64((3600*24)*nextVisitTime) + time.Now().Unix()
        customerInfo.ToRecord = []visit.CrmVisitRecord{visit.CrmVisitRecord{
            Content: customerInfo.ExchangeContent,
            IsOk: 1,
        }}
        Db.Create(&customerInfo)
    }
    c.JSON(http.StatusOK, resp)
}

// edit customer
func Edit(c *gin.Context) {
    var customerInfo customer.Customer
    if err := c.BindJSON(&customerInfo); err != nil {
        mlog.Log.Info("c.BindJSON(&customerInfo) is failed, err: ", err)
        return
    }
    mlog.Log.Info("reqData: ", customerInfo)
    nextVisitTime, _ := strconv.Atoi(customerInfo.NextVisitDay)
    customerInfo.NextVisitAt = int64((3600*24)*nextVisitTime) + time.Now().Unix()
    resp := Response{
        Status:      1,
        Msg:    "修改成功",
    }
    err := Db.Model(&customer.Customer{}).Where("id = ?", customerInfo.ID).Updates(&customerInfo).Error
    if err != nil {
        mlog.Log.Info("err: ", err)
        resp.Status = 0
        resp.Data = err
    }
    mlog.Log.Info("resp: ", resp)
    c.JSON(http.StatusOK, &resp)
}

// del customer
// 拥有删除权限: 管理员, 最高领导 可以删除所有人的(role_id: 1, 2)
func Del(c *gin.Context) {
    delCustomerId := c.Param("delCustomerId")
    uid := c.Param("uid")
    uidNum, _ := strconv.Atoi(uid)
    var customerInfo customer.Customer
    Db.Find(&customerInfo, delCustomerId)
    resp := &Response{
        Status: 1,
        Msg:    "删除成功",
    }
    isOk := false
    if uidNum == customerInfo.UserId { // 本人
        Db.Delete(&customer.Customer{}, delCustomerId)
        isOk = true
    } else {
        // 查询当前 role_id 是否为 1 或 2, 如果是的可以删除, 不是则不能
        var toRole user.CrmUser2role
        Db.Find(&toRole, "user_id = ?", uid)
        if toRole.RoleId == 1 || toRole.RoleId == 2 {
            Db.Delete(&customer.Customer{}, delCustomerId)
            isOk = true
        } else {
            resp.Status = 0
            resp.Msg = "您没有删除权限"
        }
    }
    if isOk { // 删除关联数据
        Db.Delete(&visit.CrmVisitRecord{}, "customer_id = ?", delCustomerId)
    }
    c.JSON(http.StatusOK, resp)
}
